package listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;

@WebListener
public class SessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session=httpSessionEvent.getSession();
        ServletContext context=session.getServletContext();
//        System.out.println("user session");
//        System.out.println(session.getId());
        List<String>listUser= (List<String>) context.getAttribute("listUser");
        listUser.add(session.getId());
        context.setAttribute("listUser",listUser);

        Integer onlineNum= (Integer) context.getAttribute("onlineNum");
        context.setAttribute("onlineNum",++onlineNum);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session=httpSessionEvent.getSession();
        ServletContext context=session.getServletContext();
        Integer onlineNum= (Integer) context.getAttribute("onlineNum");
        context.setAttribute("onlineNum",--onlineNum);
    }
}
